package cn.jc.springframework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import cn.jc.springframework.beans.BeansException;
import cn.jc.springframework.beans.factory.DisposableBean;
import cn.jc.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * @Description:销毁方法适配器
 * @author: JC
 * @date: 2023/4/7 13:07
 */
public class DisposableBeanAdapter implements DisposableBean {

    private final String beanName;
    private final Object bean;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }


    @Override
    public void destroy() throws Exception {
        // 1. 实现接口 DisposableBean
        if(this.bean instanceof DisposableBean){
            ((DisposableBean)bean).destroy();
        }

        // 2. 配置信息 destroy-method {判断是为了避免二次执行销毁}
        if(StrUtil.isNotEmpty(this.destroyMethodName) && !(this.bean instanceof
                DisposableBean && "destroy".equals(this.destroyMethodName))){

            Method method = this.bean.getClass().getMethod(this.destroyMethodName);
            if (null == method) {
                throw new BeansException("Couldn't find a destroy method named '" +
                        this.destroyMethodName + "' on bean with name '" + this.beanName + "'");
            }

            method.invoke(this.bean);
        }
    }
}
